function selectDisplayTask(Tabs){if(getCurrentTabData().type=="Group")displayGroupTask(Tabs); else displaySingleTask(Tabs);}
function displaySingleTask(Tabs){displayTaskDetailPage(Tabs.Task,$(".TaskNoteList:visible"));}

function displayGroupTask(Tabs){
	if(Tabs.GroupResvList == null)return;
	var tmp = {};
	tmp = [].concat(Tabs.Task);
	for(i=0;i<Tabs.GroupResvList.length;i++)
		if(Tabs.GroupResvList[i].Task!=null)
			tmp = $.merge(tmp,Tabs.GroupResvList[i].Task);
	displayTaskDetailPage(tmp,$(".TaskNoteList:visible"));
}

function displayTaskDetailPage(Task,dom){
	dom.children().remove();
	if(Task == null || Task[0]==null)
		return;

	var Tabs = getCurrentTabData();
	$("[group=sortTask]").find("span").remove();
	if(Tabs.SortTask != null){
		if(Tabs.SortTask.Field=='id' && Tabs.SortTask.Type=="desc") Task.sort(function(a, b) {return b.id - a.id});
		else if(Tabs.SortTask.Field=='id' && Tabs.SortTask.Type=="asc") Task.sort(function(a, b) {return a.id - b.id});
		else if(Tabs.SortTask.Field=='star' && Tabs.SortTask.Type=="desc") Task.sort(function(a, b) {return b.isStar - a.isStar});
		else if(Tabs.SortTask.Field=='star' && Tabs.SortTask.Type=="asc") Task.sort(function(a, b) {return a.isStar - b.isStar});
		else if(Tabs.SortTask.Field=='title' && Tabs.SortTask.Type=="desc") Task.sort(function(a, b) {return b.taskTitle > a.taskTitle});
		else if(Tabs.SortTask.Field=='title' && Tabs.SortTask.Type=="asc") Task.sort(function(a, b) {return a.taskTitle > b.taskTitle});
		else if(Tabs.SortTask.Field=='due' && Tabs.SortTask.Type=="desc") Task.sort(function(a, b) {return new Date(b.due) - new Date(a.due)});
		else if(Tabs.SortTask.Field=='due' && Tabs.SortTask.Type=="asc") Task.sort(function(a, b) {return new Date(a.due) - new Date(b.due)});
		else if(Tabs.SortTask.Field=='note' && Tabs.SortTask.Type=="desc") Task.sort(function(a, b) {return (b.detail!="") - (a.detail!="")});
		else if(Tabs.SortTask.Field=='note' && Tabs.SortTask.Type=="asc") Task.sort(function(a, b) {return (a.detail!="") - (b.detail!="")});
		fillSortIcon(Tabs.SortTask.dom,Tabs.SortTask.Type);
	}
	else 
		Task.sort(function(a, b) {return a.id - b.id});
	var taskString = "";
	dom.parents("table:first").find("[name=total]").html(Task.length);
	for(i=0;i<Task.length;i++)
	{
		var addedClass = "";
		if(!Task[i].isSetDue)
			date = task_defineduedate;
		else{
			var due = new Date(Task[i].due);
			var minW = SharedData.General.minuteForWarning;
			var minC = SharedData.General.minuteForCritical;
			if(due.addMin(minW*-1) <= getServerDateTime() && getServerDateTime() < due.addMin(minC*-1)) 
				addedClass = " warNingStatus";
			else if(getServerDateTime() >= due.addMin(minC*-1))
				addedClass = " criTicalStatus";
			date = due.getFormatedString() + "&nbsp; &nbsp;" + due.getHours() + ":" + due.getMinutes();
		}
		var trashicon = (Task[i].isTrash)?"../images/components/task/trash/fulltrash.png":"../images/components/task/trash/emptytrash.png";

		var checked = "";
		if (Task[i].isComplete)
			checked="checked=\"checked\"";
		var stringFormat = '<tr class="{7}'+addedClass+'" refid="{0}" style="vertical-align:middle;">'+
			'<td style="width:13%;text-align:center;" onclick="checkTaskTaskNote($(this));"><input type="checkbox" class="css-checkbox"'+checked+'><label class="css-label mac-style">{1}</label></td>'+
			'<td style="width:5%;text-align:center;"><span onclick="starTaskTaskNote($(this));" style="cursor:pointer;"><img src="{2}" alt="Star Task" height="20" width="20"></span></td>'+
			'<td style="width:40%;text-align:left;padding-left:8px;"><span class="link'+addedClass+'" onclick="fillSimpleTextEdit($(this),false,editTaskNoteTitle)">{3}</span>'+
			'<td style="width:25%;text-align:left;padding-left:8px;"><span class="link'+addedClass+'" onclick="EditDueTaskNote($(this))">{4}</span></td>'+
			'<td style="width:22%;text-align:center;"><span onclick="EditDetailTaskNote($(this));" style="cursor:pointer;"><img src="{5}" alt="Note" height="20" width="20"></span>&nbsp; &nbsp;<span onclick="MoveTrashTaskNote($(this));" style="cursor:pointer;"><img src="{6}" alt="Note" height="20" width="20"></span></td>'+
		'</tr>';

		taskString += stringFormat.format(
			Task[i].id,
			Task[i].id,
			(Task[i].isStar)? "/images/components/task/staricon/gold.png":"/images/components/task/staricon/silver.png",
			(Task[i].taskTitle=="")?"-":Task[i].taskTitle,
			date,
			(Task[i].detail == 0 || Task[i].detail == null)? "/images/components/task/foldericon/white.png":"/images/components/task/foldericon/yellow.png",
			trashicon,
			(Task[i].isTrash)? "lineDelete": "lineTable"
		);
	}
	if(taskString!="")
		taskString = '<table border="0" width="100%"><tbody>' + taskString + '</tbody></table>';
	dom.html(taskString);
}

function fillSortIcon(e,t){var n=e.attr("group");if(t=="desc")e.append("<span>▼</span>");else if(t=="asc")e.append("<span>▲</span>")}

function EditDueTaskNote(obj){
	SelectDateTimePicker(obj.get(0),"top",getDate(),null,function(val,dom,isChanged){
		if(!isChanged) return;
		var date = val.split("&nbsp; &nbsp;")[0].getDate();
		var hour = (val.split("&nbsp; &nbsp;")[1]!=null)? val.split("&nbsp; &nbsp;")[1].split(":")[0]:"00";
		var min = (val.split("&nbsp; &nbsp;")[1]!=null)? val.split("&nbsp; &nbsp;")[1].split(":")[1]:"00";
		date.setHours(hour);
		date.setMinutes(min);
		var refid = dom.parents("tr:first").attr("refid");
		var link = "/taskService?func=editDue&due="+date.toFormatString("yyyy-MM-dd hh:mm")+"&id_int="+refid;
		componentLoading($(".TaskNoteList:visible"));
		simpleserviceWithError(link,null,function(data,Tabs){
		var objArray = JSON.parse(data);
		var checkLogOut = CheckSession(objArray);
		if(checkLogOut)
			return;
		closeComponentLoading($(".TaskNoteList:visible"));
		fillCallBackTask(data);
		},function(data,Tabs){closeComponentLoading($(".TaskNoteList:visible"));selectDisplayTask(Tabs);},getCurrentTabData());
	},0,0,true);
}

function editTaskNoteTitle(obj){
	if(obj.dom.text() == obj.textbox.val()) return;
	var resId = obj.dom.parents("tr:first").attr("refid");
	var link = "/taskService?func=editTitle&title=" + obj.textbox.val()+"&id_int="+resId;
	componentLoading($(".TaskNoteList:visible"));
	simpleserviceWithError(link,null,function(data,Tabs){
		var objArray = JSON.parse(data);
		var checkLogOut = CheckSession(objArray);
		if(checkLogOut)
			return;
		closeComponentLoading($(".TaskNoteList:visible"));
		fillCallBackTask(data);
	},function(data,Tabs){closeComponentLoading($(".TaskNoteList:visible"));selectDisplayTask(Tabs);},getCurrentTabData());
}

function MoveTrashTaskNote(obj){
	var tr = obj.parents("tr:first");
	var trash = (obj.find("img").attr("src") != "../images/components/task/trash/fulltrash.png");
	var link = "/taskService?func=editTrash&id_int="+tr.attr("refid")+'&trash='+trash;
	componentLoading($(".TaskNoteList:visible"));
	simpleserviceWithError(link,null,function(data,Tabs){
		var objArray = JSON.parse(data);
		var checkLogOut = CheckSession(objArray);
		if(checkLogOut)
			return;
		closeComponentLoading($(".TaskNoteList:visible"));
		fillCallBackTask(data);
	},function(data,Tabs){closeComponentLoading($(".TaskNoteList:visible"));selectDisplayTask(Tabs);},getCurrentTabData());
}

function starTaskTaskNote(obj){
	var tr = obj.parents("tr:first");
	var isstar = tr.find("[alt*=Star][src*=silver]").size()==0;
	var link = "/taskService?func=editStar&status_star=" + isstar+"&id_int="+tr.attr("refid");
	componentLoading($(".TaskNoteList:visible"));
	simpleserviceWithError(link,null,function(data,Tabs){
		var objArray = JSON.parse(data);
		var checkLogOut = CheckSession(objArray);
		if(checkLogOut)
			return;
		closeComponentLoading($(".TaskNoteList:visible"));
		fillCallBackTask(data);
	},function(data,Tabs){closeComponentLoading($(".TaskNoteList:visible"));selectDisplayTask(Tabs);},getCurrentTabData());
}

function checkTaskTaskNote(obj){
	var tr = obj.parents("tr:first");
	var ischeck = (obj.find("input[type=checkbox]").is(":checked"));
	var link = "/taskService?func=editClose&complete="+ischeck+"&id_int="+tr.attr("refid");
	componentLoading($(".TaskNoteList:visible"));
	simpleserviceWithError(link,null,function(data,Tabs){
		var objArray = JSON.parse(data);
		var checkLogOut = CheckSession(objArray);
		if(checkLogOut)
			return;
		closeComponentLoading($(".TaskNoteList:visible"));
		fillCallBackTask(data);
	},function(data,Tabs){closeComponentLoading($(".TaskNoteList:visible"));selectDisplayTask(Tabs);},getCurrentTabData());
}

function EditDetailTaskNote(obj){
	var tr = obj.parents("tr:first");
	if(tr.next().attr("type")=="Detail") selectDisplayTask(getCurrentTabData());
	var refid = tr.attr("refid");
	var task = getLocalTaskFromId(refid);
	var textbox = '<textarea rows="4" style="margin: 2px; width: 475px; max-width: 475px; height: 45px;"></textarea>';
	tr.after("<tr refid=\""+refid+"\" style=\"height:48px;\" type=\"Detail\"><td colspan='5' style=\"text-align:right;\">"+textbox+"</td></tr>");
	var textbox = tr.next().find("textarea");
	textbox.val(task.detail);
	textbox.focus();

	textbox.blur(function(e){
		var refid = $(e.target).parents("tr:first").attr("refid");
		var task = getLocalTaskFromId(refid);
		if(task.detail != $(e.target).val()) updateDetailTask(refid,$(e.target)); else selectDisplayTask(getCurrentTabData());
	});
}

function getLocalTaskFromId(refid){
	var task = null;
	var Tabs = getCurrentTabData();
	for(i=0;i<Tabs.Task.length;i++)
		if(Tabs.Task[i].id == refid)
			task = Tabs.Task[i]
	if(task==null)
		for(i=0;i<Tabs.GroupResvList.length;i++)
			for(j=0;j<Tabs.GroupResvList[i].Task.length;j++)
				if(Tabs.GroupResvList[i].Task[j].id == refid){
					task = Tabs.GroupResvList[i].Task[j];
					break;
				}
	return task;
}

function updateDetailTask(refid,dom){
	var link = "/taskService?func=editDetail&detail="+dom.val()+"&id_int="+refid;
	componentLoading($(".TaskNoteList:visible"));
	simpleserviceWithError(link,null,function(data,Tabs){
		var objArray = JSON.parse(data);
		var checkLogOut = CheckSession(objArray);
		if(checkLogOut)
			return;
		closeComponentLoading($(".TaskNoteList:visible"));
		fillCallBackTask(data);
	},function(data,Tabs){closeComponentLoading($(".TaskNoteList:visible"));selectDisplayTask(Tabs);},getCurrentTabData());
}

function  AddTaskNote() {
	var Date_Format = "0000-00-00 00:00:00";
	var val = $("[id*=addtask][id*=_note_id]:visible").val();
	$("[id*=addtask][id*=_note_id]:visible").val("");
	var Tabs = getCurrentTabData();
	var resId = Tabs.resId;
	var link="/taskService?func=AddTaskNote&detail=&due="+Date_Format+'&isStar=false&status=Normal&taskTitle='+val+'&res_id='+ resId+"&roomName="+Tabs.ResData.roomName;
	if(Tabs.type=="Group")
		link = "/taskService?func=AddTaskNoteGroup&detail=&due="+Date_Format+'&isStar=false&status=Normal&taskTitle='+val+'&group_id='+ resId+"&roomName=G";
	componentLoading($(".TaskNoteList:visible"));
	simpleserviceWithError(link,null,function(data,Tabs){
		var objArray = JSON.parse(data);
		var checkLogOut = CheckSession(objArray);
		if(checkLogOut)
			return;
		closeComponentLoading($(".TaskNoteList:visible"));
		if(getCurrentTabData().Task==null) getCurrentTabData().Task = [];
		getCurrentTabData().Task.push(JSON.parse(data));
		selectDisplayTask(Tabs);
	},function(data,obj){closeComponentLoading($(".TaskNoteList:visible"));selectDisplayTask(Tabs);},Tabs);
}

$("#addtasksgroup_note_id").keypress(function(e) {
	if (e.keyCode == '13'&&$("#addtasksgroup_note_id").val()!="")
		AddTaskNote();
});
$("#addtasks_note_id").keypress(function(e) {
	if (e.keyCode == '13'&&$("#addtasks_note_id").val()!="")
		AddTaskNote();
});

function fillCallBackTask(data){
	var objArray = JSON.parse(data);
	var Tabs = getCurrentTabData();
	for(i=0;i<Tabs.Task.length;i++)
		if(Tabs.Task[i].id == objArray.id)
			Tabs.Task[i] = objArray;
	selectDisplayTask(Tabs);
}

function sortTask(dom,field){
	var Tabs = getCurrentTabData();
	if(Tabs.SortTask == null || JSON.stringify(Tabs.SortTask.Field) != JSON.stringify(field)){
		Tabs.SortTask = {};
		Tabs.SortTask.Type = "desc";
		Tabs.SortTask.Field = field;
		Tabs.SortTask.dom = dom;
	}
	else if(Tabs.SortTask.Type == "desc"){
		Tabs.SortTask.Type = "asc";
		Tabs.SortTask.Field = field;
		Tabs.SortTask.dom = dom;
	}
	else if(Tabs.SortTask.Type == "asc")
		delete Tabs.SortTask;
	selectDisplayTask(Tabs);
}

function checkInSingleInGroupProcess(){
	var selected = $("#resvList tr[resId] input[type=checkbox]:checked");
	if(selected.length == 0) return;
	var mergeId = $(selected[0]).parents("tr").attr("resId");
	for(var i=1;i<selected.length;i++)
		mergeId += "," + $(selected[i]).parents("tr").attr("resId");
	simpleservice("/reservationService",{func:"CheckInResvList",listResId:mergeId},checkInSingleInGroupProcessSuccess);
}

function checkInSingleInGroupProcessSuccess(data)
{
	var objArray = JSON.parse(data);
	for(var i=0;i<objArray.length;i++)
		EditResvStatus(objArray[i].resId,objArray[i].Status.title,objArray[i].Status.id);
	DisplayDetail();
	cerltimespan(savedSpan);
	closeWaitingDialog();
}
//////End change Status Check out All
function showCancelRes(){
	if($(".cancel-res-display-none").css('display')=='none'){
		$(".cancel-res-display-none").show('slow');
		$( "#show-cancel-res" ).html("ซ่อนห้องที่ยกเลิกการจอง");
	}else{
		$(".cancel-res-display-none").hide(1000);
		$( "#show-cancel-res" ).html("แสดงห้องที่ยกเลิกการจอง");
	}
}

// Detail page button event group
function btnClosePage()
{	var id = getCurrentTabData().resId;
	var title = "editreserved"+id;
	CloseTapPage(title);
}
function btnEarlyCheckOut(){
	var status ="Checked-out Rooms";
	var sellRooms = false;
	var type ="EarlyCheckout";
	FillChargeReason(status,sellRooms,type);
}
function  btnCheckOutAllGroup() {
	var link="/reservationService?func=getReservationGroup&groupId="+ getCurrentTabData().resId;
	simpleserviceWithArgs(link,null,CheckOutGroupSuccess,obj);	
}
function btnCancelReservation()
{
	var status ="Cancel Reservation";
	var sellRooms = false;
	var type ="CancelRes";
	var cancelCharge=initCharge();
	FillChargeReason(status,sellRooms,type);
}

function btnCheckIn() {
	var obj ={};
	obj.id = getCurrentTabData().resId;
	if(getCurrentTabData().Owner == null){simpleDialog("fill owner.",1000);return;}
	obj.sellRoom_editAfRes = false;
	obj.isAss_editAfRes = false;
	obj.roomStatus_editAfRes = SharedData.ResvStatus[1].title;
	obj.time = getServerDateTime().getHours()+":"+getServerDateTime().getMinutes()+":"+getServerDateTime().getSeconds();
	obj.nowDate =getServerDateTime().toSystemFormat()+" "+obj.time;
		if(obj.id!=0){
			var link = "/reservationService?func=editAfterRes&resId=" +obj.id+"&reservationstatus="+obj.roomStatus_editAfRes+"&sellroom="+obj.sellRoom_editAfRes+"&isassign="+obj.isAss_editAfRes+"&dateCheckin="+obj.nowDate;
			simpleserviceWithArgs(link,null,btnClickSuccess,obj);	
		}else{
			btnReservation($('<input type="button" name="payMent"setbutton="emptyCheckin">'));
		}
}

function cancelbtnCheckIn() {
	FillChargeReason("Reserved Rooms",false,"CancelCheckin");
}

function btnCheckOut() {
	var obj ={};
	obj.id = getCurrentTabData().resId;
	obj.sellRoom_editAfRes = false;
	obj.isAss_editAfRes = false;
	obj.roomStatus_editAfRes = "Checked-out Rooms";
	obj.time = getServerDateTime().getHours()+":"+getServerDateTime().getMinutes()+":"+getServerDateTime().getSeconds();
	obj.nowDate =getServerDateTime().toSystemFormat()+" "+obj.time;

	var link="/reservationService?func=editAfterRes&resId=" +obj.id+"&reservationstatus="+obj.roomStatus_editAfRes+"&sellroom="+obj.sellRoom_editAfRes+"&isassign="+obj.isAss_editAfRes+"&dateCheckin="+obj.nowDate;
	simpleserviceWithArgs(link,null,btnClickSuccess,obj);
}
function cancelbtnCheckOut() {
	FillChargeReason("Checked-in Rooms",false,"CancelCheckout");
}

function btnReservation(e){	 
	var TabsBookingG = getCurrentTabData().ResData;
	if(getCurrentTabData().Owner == null){simpleDialog("fill owner.",1000);return;}
	var obj ={};
	obj.id = getCurrentTabData().resId;
	obj.sellRoom_editAfRes = false;
	obj.isAss_editAfRes = false;
	if($(e).attr("setButton") == "reservation")
		obj.roomStatus_editAfRes = "Reserved Rooms";
	else if($(e).attr("setButton") == "payMent")
	{
		obj.roomStatus_editAfRes = "Reserved Rooms";
		TabsBookingG.isAssign = true;
	}
	else if($(e).attr("setButton") == "emptyCheckin"){
		obj.roomStatus_editAfRes = "Checked-in Rooms";
		TabsBookingG.isAssign = true;
	}else
		obj.roomStatus_editAfRes = "Temp Rooms";

	obj.time = getServerDateTime().getHours()+":"+getServerDateTime().getMinutes()+":"+getServerDateTime().getSeconds();
	obj.nowDate =getServerDateTime().toSystemFormat()+" "+obj.time;
	obj.roomTypeId = TabsBookingG.roomTypeString;
	obj.roomId = TabsBookingG.roomString;
	obj.from = $("[id*=edit_res_resdetails_checkin]:visible").text().getDate();
	to = $("[id*=edit_res_resdetails_checkout]:visible").text().getDate();	
	obj.span = daysBetween(obj.from,to);
	if(obj.id != 0)
		var link ="/reservationService?func=editAfterRes&resId=" +obj.id+"&reservationstatus="+obj.roomStatus_editAfRes+"&sellroom="+obj.sellRoom_editAfRes+"&isassign="+obj.isAss_editAfRes+"&dateCheckin="+obj.nowDate;
	else
		var link = "/reservationService?func=CreateRes"
		+ "&date=" + obj.from.toSystemFormat() + "&span=" + obj.span + "&rmId=" + obj.roomId
		+ "&rmType=" +obj.roomTypeId + "&priceRate="+TabsBookingG.priceRateString
		+"&adult="+TabsBookingG.adult+"&child="+TabsBookingG.child
		+"&isA="+TabsBookingG.isAssign+"&guest=0&ReservationStatus=" + obj.roomStatus_editAfRes
		+ "&sal="+TabsBookingG.salutation+"&nm="+TabsBookingG.guestName
		+"&lsNm="+TabsBookingG.guestLastName+"&phone="+TabsBookingG.guestTel
		+"&mail="+TabsBookingG.email+"&roomamount="+TabsBookingG.order
		+"&agency="+TabsBookingG.agency+"&agencyId=0&pay="+TabsBookingG.pay;
	simpleserviceWithArgs(link,null,btnClickSuccess,obj);
}
 
function  btnCheckInAllGroup() {
	var obj ={};
		obj.resList=[];
		var Tabs = getCurrentTabData();
		if(Tabs.Owner.id == null){simpleDialog("fill group owner.",1000);return;}
		if($('[name=edit_res_detail_guestname]:visible').find('[guestId=0]').size()!=0){simpleDialog("fill room owner.",1000);return;}
		if(Tabs.GroupResvList != null){
			for(var i =0;i<Tabs.GroupResvList.length;i++)
				obj.resList.push(Tabs.GroupResvList[i].resId);
		}
		obj.sellRoom_editAfRes = false;
		obj.isAss_editAfRes = true;
		obj.roomStatus_editAfRes = "Checked-in Rooms";
		obj.time = getServerDateTime().getHours()+":"+getServerDateTime().getMinutes()+":"+getServerDateTime().getSeconds();
		obj.nowDate =getServerDateTime().toSystemFormat()+" "+obj.time;

		if(Tabs.resId!=0){
			var link ="/reservationService?func=editAfterRes&resId=" +obj.resList+"&reservationstatus="+obj.roomStatus_editAfRes+"&sellroom="+obj.sellRoom_editAfRes+"&isassign="+obj.isAss_editAfRes+"&dateCheckin="+obj.nowDate;
			simpleserviceWithArgs(link,null,btnClickSuccess,null);
		}
		else
		{
			var data={};
			if(Tabs.GroupResvList == null)
			{
				var pack = getObjectFromSharedData(SharedData.Package,Tabs.ResData.priceRateString);
				var span =daysBetween($("#edit_res_resdetails_checkin").text().getDate(),$("#edit_res_resdetails_checkout").text().getDate());
				var roomnameId =[];
				var roontypeId=[];
				for(var i=0;i<parseInt(Tabs.ResData.order);i++)
				{
					roomnameId.push(0);
					roontypeId.push($($("tr[refId="+(i+1)+"]").find($("td"))[2]).find("span").attr("roomtypeid"))
				}
				data = {
					func: "createGroupandAddRes",
					roomtypeNew: roontypeId.toString(),
					roomNew: roomnameId.toString(),
					roomStatusNew: getObjectFromDataIndex(SharedData.ResvStatus,"title","Checked-in Rooms").id,
					guestNameNew: "",
					guestLastNameNew: "",
					guestIdNew:Tabs.Owner.id,
					telNew: "",
					adultNew: 1,
					childNew: 0,
					packageNew: Tabs.ResData.priceRateString,
					priceNew: getObjectFromDataIndex(pack.packagepriceList,"roomtypeString",roontypeId[0]).priceperNight,
					dateNew: $("#edit_res_resdetails_checkin").text().getDate().toSystemFormat(),
					spanNew: span,
					groupIdNew: Tabs.resId
				};
			}else{
				var roomtypeId = [];
				var roomnameId =[];
				for(var i=0;i<Tabs.GroupResvList.length;i++)
				{
					roomtypeId.push(Tabs.GroupResvList[i].ResData.roomTypeString);
					roomnameId.push(Tabs.GroupResvList[i].ResData.roomString);
				}
				data = {
					func: "createGroupandAddRes",
					roomtypeNew: roomtypeId.toString(),
					roomNew: roomnameId.toString(),
					roomStatusNew: getObjectFromDataIndex(SharedData.ResvStatus,"title",obj.roomStatus_editAfRes).id,
					guestNameNew: "",
					guestLastNameNew: "",
					guestIdNew: Tabs.Owner.id,
					telNew: "",
					adultNew: 1,
					childNew: 0,
					packageNew: Tabs.GroupResvList[0].ResData.priceRateString,
					priceNew: Tabs.GroupResvList[0].ResData.priceNew,
					dateNew: $("#edit_res_resdetails_checkin").text().getDate().toSystemFormat(),
					spanNew: Tabs.GroupResvList[0].ResData.span,
					groupIdNew: Tabs.resId
				};
			}
			simpleserviceWithArgs("/reservationService",data,btnClickSuccess,obj);
		}
 }

function btnGroupReservation() {
	var Tabs = getCurrentTabData();
	if(Tabs.Owner.id == null){simpleDialog("fill group owner.",1000);return;}
	var obj ={};
	obj.resList=[];
	if(Tabs.GroupResvList != null)
		for(var i =0;i<Tabs.GroupResvList.length;i++)
			obj.resList.push(Tabs.GroupResvList[i].resId);
	obj.sellRoom_editAfRes = false;
	obj.isAss_editAfRes = true;
	obj.roomStatus_editAfRes = "Reserved Rooms";
	obj.time = getServerDateTime().getHours()+":"+getServerDateTime().getMinutes()+":"+getServerDateTime().getSeconds();
	obj.nowDate =getServerDateTime().toSystemFormat()+" "+obj.time;

	if(Tabs.resId!=0){
		var link ="/reservationService?func=editAfterRes&resId=" +obj.resList+"&reservationstatus="+obj.roomStatus_editAfRes+"&sellroom="+obj.sellRoom_editAfRes+"&isassign="+obj.isAss_editAfRes+"&dateCheckin="+obj.nowDate;
		simpleserviceWithArgs(link,null,btnClickSuccess,null);
	}
	else
	{	
		var data={};
		if(Tabs.GroupResvList == null)
		{
			var pack = getObjectFromSharedData(SharedData.Package,Tabs.ResData.priceRateString);
			var span =daysBetween($("#edit_res_resdetails_checkin").text().getDate(),$("#edit_res_resdetails_checkout").text().getDate());
			var roomnameId =[];
			var roomtypeId=[];
				for(var i=0;i<parseInt(Tabs.ResData.order);i++)
				{
					roomnameId.push(0);
					roomtypeId.push($($("tr[refId="+(i+1)+"]").find($("td"))[2]).find("span").attr("roomtypeid"))
				}
			data = { 
				func: "createGroupandAddRes",
				roomtypeNew: roomtypeId.toString(),
				roomNew: roomnameId.toString(),
				roomStatusNew: getObjectFromDataIndex(SharedData.ResvStatus,"title","Reserved Rooms").id,
				guestNameNew: "",
				guestLastNameNew: "",
				guestIdNew:Tabs.Owner.id,
				telNew: "",
				adultNew: 1,
				childNew: 0,
				packageNew: Tabs.ResData.priceRateString,
				priceNew: getObjectFromDataIndex(pack.packagepriceList,"roomtypeString",roomtypeId[0]).priceperNight,
				dateNew: $("#edit_res_resdetails_checkin").text().getDate().toSystemFormat(),
				spanNew: span,
				groupIdNew: Tabs.resId
			};
		}else{
			var roomtypeId = [];
			var roomnameId =[];
			for(var i=0;i<Tabs.GroupResvList.length;i++)
			{
				roomtypeId.push(Tabs.GroupResvList[i].ResData.roomTypeString);
				roomnameId.push(Tabs.GroupResvList[i].ResData.roomString);
			}
			data = {
				func: "createGroupandAddRes",
				roomtypeNew: roomtypeId.toString(),
				roomNew: roomnameId.toString(),
				roomStatusNew: getObjectFromDataIndex(SharedData.ResvStatus,"title","Reserved Rooms").id,
				guestNameNew: "",
				guestLastNameNew: "",
				guestIdNew:Tabs.Owner.id,
				telNew: "",
				adultNew: 1,
				childNew: 0,
				packageNew: Tabs.GroupResvList[0].ResData.priceRateString,
				priceNew: Tabs.GroupResvList[0].ResData.priceNew,
				dateNew: $("#edit_res_resdetails_checkin").text().getDate().toSystemFormat(),
				spanNew: Tabs.GroupResvList[0].ResData.span,
				groupIdNew: Tabs.resId
			};
		}
		simpleserviceWithArgs("/reservationService",data,btnClickSuccess,obj);
	}
}
 
function GroupTempReseration ()
{
	var Tabs=getCurrentTabData();
	if(Tabs.Owner.id == null){simpleDialog("fill group owner.",1000);return;}
	var pack = getObjectFromSharedData(SharedData.Package,Tabs.ResData.priceRateString);
	var span =daysBetween($("#edit_res_resdetails_checkin").text().getDate(),$("#edit_res_resdetails_checkout").text().getDate());
	var roomnameId =[];
	var roontypeId=[];
		for(var i=0;i<parseInt(Tabs.ResData.order);i++)
		{
			roomnameId.push(0);
			roontypeId.push($($("tr[refId="+(i+1)+"]").find($("td"))[2]).find("span").attr("roomtypeid"))
		}
	var data = {
		func: "createGroupandAddRes",
		roomtypeNew: roontypeId.toString(),
		roomNew: roomnameId.toString(),
		roomStatusNew: getObjectFromDataIndex(SharedData.ResvStatus,"title","Temp Rooms").id,
		guestNameNew: "",
		guestLastNameNew: "",
		guestIdNew: 0,
		telNew: "",
		adultNew: 1,
		childNew: 0,
		packageNew: Tabs.ResData.priceRateString,
		priceNew: getObjectFromDataIndex(pack.packagepriceList,"roomTypeId",roontypeId[0]).priceperNight,
		dateNew: $("#edit_res_resdetails_checkin").text().getDate().toSystemFormat(),
		spanNew: span,
		groupIdNew: Tabs.resId
	};
	simpleserviceWithArgs("/reservationService",data,btnClickSuccess,null);
}

function btnClickSuccess(data,obj)
{
	closeWaitingDialog();
	setTimeout(function(){showNumberall_reservation();},50);
	var objArray = JSON.parse(data);
	if(objArray == null)
		simpleDialog(saveFail_label,100,null);
	else
	{
		var checkLogOut =  CheckSession(objArray);
		if(checkLogOut)
			return;
		$("[name = edit_groups]").css("display","none");
		$("[name=edit_none_groups]").css("display","none");
		CloseTapPage($("[id*=tappage_roommanage_menu_editreserved][class=select]").attr("title"));
		cerltimespan($(".timespanbuttonactive").get(0));
	}
}
function btnearyCheckIn()
{
	var Tabs = getCurrentTabData();
	if(Tabs.Owner.id == null){simpleDialog("fill group owner.",1000);return;}
	FillChargeReason("Checked-in Rooms",false,"EarlyCheckin");
}
function btnlatecheckOut()
{
	FillChargeReason("Checked-out Rooms",false,"LateCheckout");
}
function btnGroupcancelCheckout()
{
	FillChargeReason();
}

function btnChargeNoShow()
{
	var status ="Cancel Reservation";
	var sellRooms = false;
	var type ="Noshow";
	var charge =initCharge();
	FillChargeReason(status,sellRooms,type,charge);
}

function CancelGroupReservation()
{
	var tr = $('tr [name*=edit_res_detail_at]:visible:checked').parents("tr").not($('tr').not('[resid]'));
	var room = tr.find("[name='edit_res_detail_rooms'] span");
	var roomsAry =[]; for(var i=0;i<room.size();i++){ roomsAry.push($(room[i]).attr('roomid'));}
	var resIdAry =[]; for(var i=0;i<tr.size();i++){ resIdAry.push($(tr[i]).attr('resid'));}
	var status ="Cancel Reservation";
	var resType="Single";
	var sellRooms = false;
	var type ="CancelRes";
	var AssignSat = false;
	var autoCharge=initCharge(resIdAry);

	FillGroupChargeReason(status,sellRooms,type,roomsAry,resType,resIdAry,AssignSat,null,autoCharge);
}
function GroupEarlyCheck()
{
	var tr = $('tr [name*=edit_res_detail_at]:visible:checked').parents("tr").not($('tr').not('[resid]'));
	var room = tr.find("[name='edit_res_detail_rooms'] span");
	var roomsAry =[]; for(var i=0;i<room.size();i++){ roomsAry.push($(room[i]).attr('roomid'));}
	var resIdAry =[]; for(var i=0;i<tr.size();i++){ resIdAry.push($(tr[i]).attr('resid'));}
	var resType="Single";
	var status ="Checked-in Rooms";
	var sellRooms = false;
	var type="EarlyCheckin";
	var AssignSat =true;
	FillGroupChargeReason(status,sellRooms,type,roomsAry,resType,resIdAry,AssignSat);
}
function GroupSelectRoomsCheckin()
{
	var tr = $('tr [name*=edit_res_detail_at]:visible:checked').parents("tr").not($('tr').not('[resid]'));
	var resIdAry =[]; for(var i=0;i<tr.size();i++){ resIdAry.push($(tr[i]).attr('resid'));}
	var obj ={};
	obj.id = resIdAry.toString();
	obj.sellRoom_editAfRes = false;
	obj.isAss_editAfRes = true;
	obj.roomStatus_editAfRes = "Checked-in Rooms";
	obj.time = getServerDateTime().getHours()+":"+getServerDateTime().getMinutes()+":"+getServerDateTime().getSeconds();
	obj.nowDate =getServerDateTime().toSystemFormat()+" "+obj.time;
	if(obj.id !=0){
		var link = "/reservationService?func=editAfterRes&resId=" +obj.id+"&reservationstatus="+obj.roomStatus_editAfRes+"&sellroom="+obj.sellRoom_editAfRes+"&isassign="+obj.isAss_editAfRes+"&dateCheckin="+obj.nowDate;
		simpleserviceWithArgs(link,null,btnClickSuccess,obj);
	}else{
		if(getCurrentTabData().ResData.reservationStatusName != "Check-in Rooms")
			btnReservation($('<input type="button" name="payMent"setbutton="payMent">'));
	}	
}
function GroupNoShow()
{
	var Tabs = getCurrentTabData();
	var tr = $('tr [name*=edit_res_detail_at]:visible').parents("tr").not($('tr').not('[resid]'));
	var room = tr.find("[name='edit_res_detail_rooms'] span");
	var roomsAry =[]; for(var i=0;i<room.size();i++){ roomsAry.push($(room[i]).attr('roomid'));}
	var resIdAry =[]; for(var i=0;i<Tabs.GroupResvList.length;i++){ resIdAry.push($(tr[i]).attr('resid'));}
	var status ="Cancel Reservation";
	var sellRooms = false;
	var type ="Noshow";
	var resType="Single";
	var AssignSat =true;
	var autoCharge=initCharge();
	FillGroupChargeReason(status,sellRooms,type,roomsAry,resType,resIdAry,AssignSat);
}
function GrouplatecheckOut()
{
	var Tabs = getCurrentTabData();
	var resIdAry =[]; for(var i=0;i<Tabs.GroupResvList.length;i++){ resIdAry.push(Tabs.GroupResvList[i].resId);}
	var status ="Checked-out Rooms";
	var sellRooms = false;
	var type ="LateCheckout";
	var resType="Group";
	var groupId =getCurrentTabData().resId;
	var AssignSat =true;
	FillGroupChargeReason(status,sellRooms,type,null,resType,resIdAry,AssignSat,groupId);
}

function FillChargeReason(status,sellRooms,cType,Charge){
	var cancelCharge=0;
	if(Charge!=null){cancelCharge=Charge;}
	var content = $('<table class="simpleTable"><tr>' +
			'<td style="width:80px;">'+Popup_label_Cancel_Reason+' : </td>' +
			'<td><div style="display:table-cell;"><span class="margin-right"><select id="insert-reason-reason"></select></span>' +
			'Charge : <input type="text" class="currency" id="insert-reason-cost" value="'+cancelCharge+'"> <span name="unit-money"> '+SharedData.General.defaultCurrency.symbol+'</span></div></td>' +
		'</tr>'+
		'<tr><td>&nbsp;</td><td><span name="displayTime" class="link">'+Popup_label_insert_time+'</span></td></tr>' +
		'<tr name="time" style="display:none;"><td>&nbsp;</td><td>' +
			'<select></select> : <select></select>'+Popup_label_time+
		'</td></tr>' +
		'<tr><td>'+Popup_label_Cancel_detail+' : </td>' +
			'<td><textarea id="insert-cancel-resondetail" rows="2" cols="45" ></textarea>' +
		'</td></tr>' +
		'<tr><td></td><td>' +
			'<div style="display:table-cell; float:left;"><input type="checkbox" name="insert-reason-send-email" /> '+Popup_label_Cancel_SendEmail + '</div>' +
			'<div name="btnEditMail" class="link" style="float:right; display:table-cell; display:none; margin-top:4px;">'+Popup_label_Cancel_insert_mail+'</div>' +
		'</td></tr>' +
		'<tr name="insert-mail" style="display:none;"><td>&nbsp;</td>' +
			'<td><textarea id="insert-cancel-mail" rows="2" cols="45" ></textarea>' +
		'</td></tr>' +
		'</table>');

	//fill Reason
	for(var i=0;i<SharedData.CancelReason.length;i++)
		content.find("#insert-reason-reason").append(optionString.format(SharedData.CancelReason[i].id,SharedData.CancelReason[i].Description));
	for(var i=0;i<24;i++)
		content.find("[name='time'] select:first").append(optionString.format(i,i));
	for(var i=0;i<60;i+=5)
		content.find("[name='time'] select:nth-child(2)").append(optionString.format(i,i));
	content.find("#insert-reason-cost").val((0).toFixed(SharedData.General.currencyDecimalPlaces));
	content.find("#insert-reason-cost").attr("placeholder",(0).toFixed(SharedData.General.currencyDecimalPlaces));
	var Tabs =getCurrentTabData();
	var TabsBookingG =Tabs.ResData;
	var buttons = [
		{ title:Popup_btn_Cancel_resv , callback: function(thisdialog,args){
			var h = ($("[name=time]:visible").find("td:Last select:first").val()!=null)?$("[name=time]:visible").find("td:Last select:first").val():getServerDateTime().getHours().toString();
			var m = ($("[name=time]:visible").find("td:Last select:Last").val()!=null)?$("[name=time]:visible").find("td:Last select:Last").val():getServerDateTime().getMinutes().toString();
			var data={
				func:"addCharge",
				resId:Tabs.resId,
				reason:$('#insert-reason-reason').find(':selected').text(),
				description:$("#insert-cancel-resondetail").val(),
				chargeQty:"0",
				discount:"0",
				subFolio:null,
				tax:0,
				isLock:false,
				isRoomCharge:false,
				type:getCurrentTabData().type,
				chargeAmount:$("#insert-reason-cost").val(),
				chargeDate:getServerDateTime().toSystemFormat()+" "+h+":"+m,
				emailMassage:$("#insert-cancel-mail").val(),
				resStatus:status,
			    sellRoom:sellRooms,
			    isAssign:(Tabs.resId!=0)?false:true,
			    chargeType:cType,
			    groupId:0,
			    span:(Tabs.resId==0)?TabsBookingG.span:0,
			    rmId:(Tabs.resId==0)?TabsBookingG.roomString:null,
			    rmType:(Tabs.resId==0)?TabsBookingG.roomTypeString:null,
			    priceRate:(Tabs.resId==0)?TabsBookingG.priceRateString:null,
			    adult:(Tabs.resId==0)?TabsBookingG.adult:1,
			    child:(Tabs.resId==0)?TabsBookingG.child:0,
			    guest:0,
			    sal:(Tabs.resId==0)?TabsBookingG.salutation:0,
			    nm:(Tabs.resId==0)?TabsBookingG.guestName:"",
			    lsNm:(Tabs.resId==0)?TabsBookingG.guestLastName:"",
			    phone:(Tabs.resId==0)?TabsBookingG.guestTel:"",
			    mail:(Tabs.resId==0)?TabsBookingG.email:"",
			    roomamount:(Tabs.resId==0)?TabsBookingG.order:0,
			    agency:(Tabs.resId==0)?TabsBookingG.agency:"",
			    agencyId:0,
			    pay:(Tabs.resId==0)?parseFloat(TabsBookingG.pay):0
			};
			simpleserviceWithArgs("/chargeService",data,btnClickSuccess,null);
			thisdialog.dialog("close");
			
			//callCancelReaservation();
		}},
	    { title:simpleLabel_Button_Close , callback: function(thisdialog,args){
	    	thisdialog.dialog("close");
	    }}
	];
	var msgDialog = customDialog(Popup_ReasonCancellation_title,content.wrap('<div/>').parent().html(),{ width: 600},buttons,null);
	msgDialog.find("[name='displayTime']").click(function(){ msgDialog.find("[name='time']").css("display",""); });
	msgDialog.find("[name='btnEditMail']").click(function(){ msgDialog.find("[name='insert-mail']").css("display",""); });
	msgDialog.find("[name='insert-reason-send-email']").change(function(){
		if(this.checked)
			msgDialog.find("[name='btnEditMail']").css("display","");
		else{
			msgDialog.find("[name='btnEditMail']").css("display","none");
			msgDialog.find("[name='insert-mail']").css("display","none");
		}
	});
}

function CheckResBeforePayment()
{
	var Tabs = getCurrentTabData();
	if(Tabs.type == "Single")
	{	
		if(Tabs.ResData.reservationStatusName != "Temp Rooms")
			return;
		btnReservation($('<input type="button" name="reservation"setbutton="reservation">'));
	}
	else if(Tabs.type == "Group"){
		if(Tabs.resId !=0){
			var status = true;
			for(var i =0;i<Tabs.GroupResvList.length;i++)
				if(Tabs.GroupResvList[i].ResData.reservationStatusName != "Temp Rooms")
					return satus= false;
			if(status)
				btnCheckInAllGroup();
		}else
		{
			btnCheckInAllGroup();
		}
	}
}

function AutoSelectRoom()
{	
	var obj={};
	obj.tr = $('tr [name*=edit_res_detail_at]:visible:checked').parents("tr").not("[resid!=0]");
	if(obj.tr.size()==0) obj.tr = $('tr [name*=edit_res_detail_at]:visible').parents("tr").not("[resid!=0]");
	obj.roomtype = obj.tr.find("[name='edit_res_detail_roomtype'] span");
	obj.roomtypeAry =[]; for(var i=0;i<obj.roomtype.size();i++){ obj.roomtypeAry.push($(obj.roomtype[i]).attr('roomtypeid'));}
	obj.room = obj.tr.find("[name='edit_res_detail_rooms'] span");
	obj.roomsAry =[]; for(var i=0;i<obj.room.size();i++){ obj.roomsAry.push($(obj.room[i]).attr('roomid'));}
		var Tabs = getCurrentTabData();
		var pack = getObjectFromSharedData(SharedData.Package,Tabs.ResData.priceRateString);
		var span = daysBetween($("#edit_res_resdetails_checkin").text().getDate(),$("#edit_res_resdetails_checkout").text().getDate());
		var data = {
			func: "createGroupandAddRes",
			roomtypeNew: obj.roomtypeAry.toString(),
			roomNew: obj.roomsAry.toString(),
			roomStatusNew: getObjectFromDataIndex(SharedData.ResvStatus,"title","Reserved Rooms").id,
			guestNameNew: "",
			guestLastNameNew: "",
			guestIdNew: 0,
			telNew: "",
			adultNew: 1,
			childNew: 0,
			packageNew: Tabs.ResData.priceRateString,
			priceNew: getObjectFromDataIndex(pack.packagepriceList,"roomtypeString",Tabs.ResData.roomtypeString).priceperNight*span,
			dateNew: $("#edit_res_resdetails_checkin").text().getDate().toSystemFormat(),
			spanNew: span,
			groupIdNew: Tabs.resId
		};
		simpleserviceWithArgs("/reservationService",data,AutoSelectRoomSuccess,obj);
}

function AutoSelectRoomSuccess(data,obj){
	var objArray = JSON.parse(data);
	var checkLogOut = CheckSession(objArray);
	if(checkLogOut)
		return;
	if(objArray  == null)
		simpleDialog(saveFail_label,100,null);
	else{
		var Tabs = getCurrentTabData();
		for(var i=0;i<objArray.length;i++){
			objArray[i].fromGroupId = Tabs.resId;
			objArray[i].page = "Detail";
			objArray[i].type = "Single";
			objArray[i].PaymentList = null;
			objArray[i].Task = null;
			objArray[i].guest = null;
			Tabs.GroupResvList.push(objArray[i]);
		}
		showResvList(Tabs);
	}
}

function FillGroupChargeReason(status,sellRooms,cType,roomsAry,resType,resIdAry,AssignSat,groupId,autoChargeTax){
	var content ="";
	content += '<table class="simpleTable"><tr>'+
		'<td style="width:80px;">'+Popup_label_Cancel_Reason+' : </td>'+
		'<td><div style="display:table-cell;"><span class="margin-right"><select id="insert-reason-reason"></select></span> Charge :';
	if(roomsAry != null){
		for(var i= 0;i<resIdAry.length;i++ )
		{
			var autoSharge=0;
			autoSharge=(autoChargeTax!=null)?autoChargeTax[i]:0;
			content +='<div>'+
				getObjectFromSharedData(SharedData.Room,roomsAry[i]).roomName+
				'<input type="text" class="currency" name="insert-reason-cost" value="'+autoSharge+'">'+
				'<span name="unit-money">'+
				SharedData.General.defaultCurrency.symbol+'</span></div>';
		}
	}else{
		content +='<div><input type="text" class="currency" name="insert-reason-cost">'+
			'<span name="unit-money">'+
			SharedData.General.defaultCurrency.symbol+'</span></div>';
	}
	content +='</div></td></tr>'+
		'<tr><td>&nbsp;</td><td><span name="displayTime" class="link">'+Popup_label_insert_time+'</span></td></tr>' +
		'<tr name="time" style="display:none;"><td>&nbsp;</td><td>' +
		'<select></select> : <select></select>'+Popup_label_time+
		'</td></tr>' +
		'<tr><td>'+Popup_label_Cancel_detail+' : </td>' +
		'<td><textarea id="insert-cancel-resondetail" rows="2" cols="45" ></textarea>' +
		'</td></tr>' +
		'<tr><td></td><td>' +
		'<div style="display:table-cell; float:left;"><input type="checkbox" name="insert-reason-send-email" /> '+Popup_label_Cancel_SendEmail + '</div>' +
		'<div name="btnEditMail" class="link" style="float:right; display:table-cell; display:none; margin-top:4px;">'+Popup_label_Cancel_insert_mail+'</div>' +
		'</td></tr>' +
		'<tr name="insert-mail" style="display:none;"><td>&nbsp;</td>' +
		'<td><textarea id="insert-cancel-mail" rows="2" cols="45" ></textarea>' +
		'</td></tr>' +
		'</table>';
	//fill Reason
	var buttons = [
		{ title:Popup_btn_Cancel_resv , callback: function(thisdialog,args){
			var amountAry =[];$('[name*=insert-reason-cost]').each(function(){ amountAry.push($('[name*=insert-reason-cost]').val());});
			var gId =0;
			var h = ($("[name=time]:visible").find("td:Last select:first").val()!=null)?$("[name=time]:visible").find("td:Last select:first").val():getServerDateTime().getHours().toString();
			var m = ($("[name=time]:visible").find("td:Last select:Last").val()!=null)?$("[name=time]:visible").find("td:Last select:Last").val():getServerDateTime().getMinutes().toString();
			if(groupId != null)
				gId = groupId;
			var data={
				func:"addCharge",
				resId:resIdAry.toString(),
				reason:$('#insert-reason-reason').find(':selected').text(),
				description:$("#insert-cancel-resondetail").val(),
				chargeQty:"0",
				discount:"0",
				subFolio:null,
				tax:0,
				isLock:false,
				isRoomCharge:false,
				type:resType,
				chargeAmount:amountAry.toString(),
				chargeDate:getServerDateTime().toSystemFormat()+" "+h+":"+m,
				emailMassage:$("#insert-cancel-mail").val(),
				resStatus:status,
				sellRoom:sellRooms,
				isAssign:AssignSat,
				chargeType:cType,
				groupId:gId
			};
			simpleserviceWithArgs("/chargeService",data,btnClickSuccess,null);
			thisdialog.dialog("close");
			//callCancelReaservation();
		}},
		{ title:simpleLabel_Button_Close , callback: function(thisdialog,args){
			thisdialog.dialog("close");
		}}
	];
	var msgDialog = customDialog(Popup_ReasonCancellation_title,$(content).wrap('<div/>').parent().html(),{ width: 600},buttons,null);
	msgDialog.find("[name='displayTime']").click(function(){ msgDialog.find("[name='time']").css("display",""); });
	msgDialog.find("[name='btnEditMail']").click(function(){ msgDialog.find("[name='insert-mail']").css("display",""); });

	for(var i=0;i<SharedData.CancelReason.length;i++)
		$("[id*=insert-reason-reason]:visible").append(optionString.format(SharedData.CancelReason[i].id,SharedData.CancelReason[i].Description));
	for(var i=0;i<24;i++)
		$("[name='time'] select:first").append(optionString.format(i,i));
	for(var i=0;i<60;i+=5)
		$("[name='time'] select:nth-child(2)").append(optionString.format(i,i));
	$("#insert-reason-cost").val((0).toFixed(SharedData.General.currencyDecimalPlaces));
	$("#insert-reason-cost").attr("placeholder",(0).toFixed(SharedData.General.currencyDecimalPlaces));

	msgDialog.find("[name='insert-reason-send-email']").change(function(){
		if(this.checked)
			msgDialog.find("[name='btnEditMail']").css("display","");
		else{
			msgDialog.find("[name='btnEditMail']").css("display","none");
			msgDialog.find("[name='insert-mail']").css("display","none");
		}
	});
}

function initCharge(resAry)
{
	var numArray = SharedData.CancellationPolicy.slice(0);
	numArray.sort(function (a,b) {
		var atA=0;
		var atB=0;
		if(a.Days!=0)
			atA=a.Days*86400000;
		if(a.Hours!=0)
			atA=a.Hours*36000;
		if(b.Days!=0)
			atB=b.Days*86400000;
		if(b.Hours!=0)
			atB=b.Hours*36000;
		return atA-atB;
	});
	var chargePrice =[];
	var ChargeAmount =[];
	var Tabs = getCurrentTabData();
	var charge = [];
	if(Tabs.type=="Single")
		charge = Tabs.ChargeList;
	else
	{
		if(resAry!=null){
			for(var c=0;c<Tabs.GroupResvList.length;c++)
				for(var i=0;i<resAry.length;i++)
					if(Tabs.GroupResvList[c].resId == resAry[i])
						charge.push(Tabs.GroupResvList[c].ChargeList[0]);
		}else{
			for(var c=0;c<Tabs.GroupResvList.length;c++)
				charge.push(Tabs.GroupResvList[c].ChargeList[0]);
		}
	}
	if(charge.length!=0){
		for(var i=0;i<charge.length;i++){
			if(charge[i].isRoomCharge)
				ChargeAmount.push(charge[i].chargeAmount); 	
		}
	}
	var datecheckin =new Date(getCurrentTabData().ResData.date).getTime()+getcheckInTime();
	for(var n= 0;n<numArray.length;n++)
	{
		var disDate=0;
		if(numArray[n].status){
			if(numArray[n].Hours!=0){disDate=numArray[n].Hours*36000;}
			if(numArray[n].Days!=0){disDate=numArray[n].Days*86400000;}
				if((datecheckin-disDate)<getServerDateTime().getTime())
					for(var i =0;i<ChargeAmount.length;i++){
						if(numArray[n].Percentcharge)
							chargePrice.push(ChargeAmount[i]*numArray[n].value/100);
						else if(numArray[n].chargeDay)
							chargePrice.push(ChargeAmount[i]*numArray[n].value);
						else if(numArray[n].fix)
							chargePrice.push(numArray[n].value);
					}
			break;
		}	
	}
	return chargePrice;
}

function CalCulateTaxWithPolicy(charge)
{
	var chargePrice = charge;
	var url = "/taxService";
	var data = { func : "CalChargeTax", charge: chargePrice.toString(), incTax:SharedData.General.incloudetax };
	simpleservice(url,data,function(data){
		var autoShargeTax =[];

		var objArray = JSON.parse(data);
		for(var i=0;i<objArray.length;i++)
			(SharedData.General.incloudetax)?autoShargeTax.push(objArray[i].costIncludeTax):autoShargeTax.push(objArray[i].costIncludeTax-objArray[i].tax);
		return autoShargeTax;
	});
}